using System;
using System.Reflection;
using PostSharp.Extensibility;
using PostSharp.Laos;

namespace AOP
{
    [MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Struct)]
    [Serializable]
    public sealed class NotifyPropertyChangedAttribute : CompoundAspect
    {
        public override void ProvideAspects(object targetElement,
                                            LaosReflectionAspectCollection collection)
        { 
            // Get the target type.
            var targetType = (Type)targetElement; 
            // On the type, add a Composition aspect to implement the INotifyPropertyChanged interface. 
           // collection.AddAspect(targetType, new AddNotifyPropertyChangedInterfaceSubAspect());
            // Add a OnMethodBoundaryAspect on each writable non-static property. 
            foreach (PropertyInfo property in targetType.GetProperties())
            {
                if (property.DeclaringType.AssemblyQualifiedName == targetType.AssemblyQualifiedName
                    && property.CanWrite) 
                {
                    MethodInfo method = property.GetSetMethod(); 
                    if (method != null && !method.IsStatic)
                    {
                        collection.AddAspect(method,
                                             new OnPropertySetSubAspect(property.Name));
                    } 
                }
            }
        }
    }
}